﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ThridGroup.ERP.DTO.ProductionSystem;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace ThridGroup.ERP.ProductionSystem
{
    /// <summary>
    /// 排班日历服务实现
    /// </summary>
    public class ShiftScheduleService : ApplicationService, IShiftScheduleService
    {
        private readonly IRepository<ShiftScheduleModel, int> _repository;

        public ShiftScheduleService(IRepository<ShiftScheduleModel, int> repository)
        {
            _repository = repository;
        }

        /// <summary>
        /// 获取某月排班数据
        /// </summary>
        public async Task<List<ShiftScheduleDto>> GetShiftSchedules(int year, int month, string equipmentTypeCode, string teamNumber)
        {
            var start = new DateTime(year, month, 1);
            var end = start.AddMonths(1);
            var list = await _repository.GetListAsync(x =>
                x.Date >= start && x.Date < end &&
                x.EquipmentTypeCode == equipmentTypeCode &&
                x.TeamNumber == teamNumber
            );
            return ObjectMapper.Map<List<ShiftScheduleModel>, List<ShiftScheduleDto>>(list);
        }

        /// <summary>
        /// 保存或更新排班
        /// </summary>
        public async Task SaveShiftSchedule(ShiftScheduleDto dto)
        {
            if (dto.Id > 0)
            {
                var entity = await _repository.GetAsync(dto.Id);
                ObjectMapper.Map(dto, entity);
                await _repository.UpdateAsync(entity);
            }
            else
            {
                var entity = ObjectMapper.Map<ShiftScheduleDto, ShiftScheduleModel>(dto);
                await _repository.InsertAsync(entity);
            }
        }
    }
}
